package com.typhoon.spring_shiro.utils.http;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class HttpPostAndGetUtil {

	private static final String secret = "EFCGQlNoR021";
	private static final String token = "365789378986";
	private static Logger logger = LoggerFactory.getLogger(HttpPostAndGetUtil.class);

	public static String get(String url) throws Exception {

		HttpClient client = new DefaultHttpClient();
		client.getParams().setParameter("http.connection.timeout",
				new Integer(5000));
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = null;
		try {
			httpResponse = client.execute(httpGet);
		} catch (ClientProtocolException e) {
			logger.error("HttpClient execute throw ClientProtocolException : "
					+ e.getMessage());
		} catch (IOException e) {
			logger.error("HttpClient execute throw IOException : "
					+ e.getMessage());
		}
		try {
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				return paseResponse(httpResponse);
				
			} else {
				return paseResponse(httpResponse);
			}
		} catch (IllegalStateException e) {
			logger.error("httpEntity.getContent execute throw IllegalStateException : "
					+ e.getMessage());
			throw new Exception(
					"httpEntity.getContent execute throw IllegalStateException : "
							+ e.getMessage());
		} finally {
			client.getConnectionManager().shutdown();
		}
	}

	public static String post(String url, Map<String, String> params) {
		
		String body = null;
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try{
			HttpPost post = postForm(url, params);
			HttpResponse response = sendRequest(httpclient, post);
			body = paseResponse(response);
		}catch(Exception e){
			
		}finally {
			httpclient.getConnectionManager().shutdown();
		}
		return body;
	}


	private static String paseResponse(HttpResponse response) {

		HttpEntity entity = response.getEntity();
		EntityUtils.getContentCharSet(entity);
		String body = null;
		try {
			body = EntityUtils.toString(entity);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return body;
	}

	private static HttpResponse sendRequest(DefaultHttpClient httpclient,
			HttpUriRequest httpost) {

		HttpResponse response = null;
		try {
			response = httpclient.execute(httpost);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}

	private static HttpPost postForm(String url, Map<String, String> params) {

		HttpPost httpost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			nvps.add(new BasicNameValuePair(key, params.get(key)));
		}
		try {
			httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return httpost;
	}

	public static String getSign(Map<String, String> paramMap) {
		if (paramMap == null || paramMap.size() < 1) {
			return null;
		}
		Object[] key = paramMap.keySet().toArray();
		Arrays.sort(key);
		StringBuilder params = new StringBuilder();
		for (int i = 0; i < key.length; i++) {
			if ("sign".equals(key[i]) || "token".equals(key[i])) {
				continue;
			}
			params.append(paramMap.get(key[i]));
		}
		params.append(secret);
		String sign = DigestUtils.md5Hex(params.toString().getBytes());
		return sign;
	}
	public static JSONObject jsonService(Map<String, String> data, String url)
			throws IOException {
		
		data.put("token", token);
		Object[] key = data.keySet().toArray();
		Arrays.sort(key);
		StringBuilder params = new StringBuilder();
		for (int i = 0; i < key.length; i++) {
			if ("sign".equals(key[i]) || "token".equals(key[i])) {
				continue;
			}
			params.append(data.get(key[i]));
		}
		params.append(secret);
		String paramsAll = URLDecoder.decode(params.toString(), "UTF-8");
		data.put("sign", DigestUtils.md5Hex(paramsAll.getBytes("iso-8859-1")));
		JSONObject jo = JSON.parseObject(URLDecoder.decode(
				post(url, data), "UTF-8"));
		return jo;
	}

}
